import time
from datetime import timedelta, datetime

from sqlalchemy import and_
from sqlalchemy.orm import sessionmaker

from tools.dbTool import dbTool
from tools.entity import Trade, Position
from tools.tool import Tool
# from tools.trader import Trader


def goTrade():
    print("开始交易任务")
    # 获取交易数据
    # endDate = datetime.now().date() - timedelta(days=2)
    # endDateStr = endDate.strftime("%Y-%m-%d")
    # endDateStr = "2024-11-05"  # 测试
    Session = sessionmaker(bind=dbTool.getEngine())
    positions = {}
    with Session() as session:
        trades = session.query(Trade) \
            .filter(Trade.execute == 0).all()
            # .filter(and_(Trade.date >= endDateStr, Trade.execute == 0)).all()
        # 查询持仓
        items = session.query(Position).all()
        for item in items:
            positions[item.code] = item
    print(f"待交易列表: {trades}")
    if len(trades) == 0:
        return
    Trader.connect()
    # print(f"当前持仓: {position}")
    for trade in trades:
        code = Tool.getCodeNum(trade.code)
        # code = '000001'  # 测试
        # break
        try:
            if code in positions:
                position = positions[code]
            else:
                position = Position(code=code, amount=0)

            amount = trade.amount
            if amount < 0:
                if abs(amount) > position.amount:
                    amount = -position.amount
                    position.amount = 0
            else:
                position.amount += amount
            res, price = Trader.market_trade(code, amount)
            trade.execute = 1
            trade.deal_price = price
            trade.trade_info = str(res)
            time.sleep(3)
            if amount > 0 or code in positions:
                dbTool.save(position)
        except Exception as e:
            trade.trade_info = str(e)
            print("交易失败: " + str(e))
        dbTool.save(trade)
        # break
    print("交易任务完成")


if __name__ == '__main__':
    goTrade()
